package com.excilys.capicsoubank.client;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class UsernamePasswordCallback implements CallbackHandler {

	@Autowired
	private ShaPasswordEncoder passwordEncoder;

	private String password;

	public String getPassword() {
		return password;
	}

	public void setPassword(String username, String password) {
		this.password = passwordEncoder.encodePassword(password, username);
	}

	@Override
	public void handle(Callback[] callbacks) throws IOException,
			UnsupportedCallbackException {

		WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];

		if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN
				&& password != null) {
			pc.setPassword(password);
		}
	}
}
